package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.abstracts.AbstractCrmUpdateDataService;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasProcessDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.PaymentSheetTypeEnum;
import com.xbongbong.paas.help.UserHelp;
import com.xbongbong.paas.pojo.dto.FormDataUpdateDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.pojo.vo.FormDataUpdateVO;
import com.xbongbong.paas.service.ProModelService;
import com.xbongbong.paas.service.dynamic.crm.strategy.DynamicStrategyFactory;
import com.xbongbong.paas.service.dynamic.crm.strategy.MainBusinessDynamicStrategy;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.pro.domain.entity.ReRollBackEntity;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicUpdateDTO;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.AfterSavePojo;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.formdata.pojo.vo.BeforeUpdateVO;
import com.xbongbong.pro.formdata.pojo.vo.UpdateVO;
import com.xbongbong.pro.message.pojo.dto.ConsistencySyncRabbitMqDTO;
import com.xbongbong.pro.payment.pojo.dto.PaymentDTO;
import com.xbongbong.pro.paymentsheet.pojo.dto.batch.PaymentSheetDTO;
import com.xbongbong.pro.paymentsheet.pojo.vo.batch.PaymentSheetAmountVO;
import com.xbongbong.pro.rabbitmq.producer.ConsistencySyncProducer;
import com.xbongbong.pro.thread.ThreadPoolBeanConfig;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ContractProductEntity;
import com.xbongbong.saas.domain.entity.ContractUserEntity;
import com.xbongbong.saas.domain.entity.ext.ContractEntityExt;
import com.xbongbong.saas.enums.ProjectLogEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.help.SaasSaveHelp;
import com.xbongbong.saas.help.workflow.MarketActivityForStaticHelp;
import com.xbongbong.saas.model.ContractModel;
import com.xbongbong.saas.model.ContractProductModel;
import com.xbongbong.saas.model.ContractUserModel;
import com.xbongbong.saas.service.ContractService;
import com.xbongbong.saas.service.PaymentService;
import com.xbongbong.saas.service.PaymentSheetService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.workflow.domain.entity.WorkflowBackupDataEntity;
import com.xbongbong.workflow.model.WorkflowBackupDataModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/02/23 16:03
 */
@Service("contractFormDataUpdateServiceImpl")
public class ContractFormDataUpdateServiceImpl extends AbstractCrmUpdateDataService {

    private static final Logger LOG = LoggerFactory.getLogger(ContractFormDataUpdateServiceImpl.class);

    @Resource
    private UserHelp userHelp;
    @Resource
    private ConsistencySyncProducer consistencySyncProducer;
    @Resource
    private ProModelService proModelService;
    @Resource
    private SaasSaveHelp saasSaveHelp;
    @Resource
    private ContractModel contractModel;
    @Resource
    private ContractService contractService;
    @Resource
    private PaymentSheetService paymentSheetService;
    @Resource
    private PaymentService paymentService;
    @Resource
    private ContractUserModel contractUserModel;
    @Resource
    private WorkflowBackupDataModel workflowBackupDataModel;
    @Resource
    private ContractProductModel contractProductModel;
    @Resource
    private ThreadPoolBeanConfig threadPoolBeanConfig;
    @Resource
    private DynamicStrategyFactory dynamicStrategyFactory;
    @Resource
    private MarketActivityForStaticHelp marketActivityForStaticHelp;


    @Override
    public List<Integer> businessType() {
        return Arrays.asList(XbbRefTypeEnum.CONTRACT.getCode());
    }


    @Override
    public UpdateVO update(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) throws XbbException {
        UpdateVO updateVO = null;
        try {
            UserVO userVO = userHelp.getUserName(formDataUpdateDTO.getCorpid(), formDataUpdateDTO.getUserId(), formDataUpdateDTO.getLoginUserName(), beforeUpdateVO.getPaasFormDataEntity().getFlowStatus(), beforeUpdateVO.getPaasFormDataEntity().getCreatorId());
            Integer noApprovalRequired = beforeUpdateVO.getNoApprovalRequired();
            Integer updateLine = 0;
            if ( Objects.equals(noApprovalRequired, 1) ) {
                JSONObject data = paasFormDataEntity.getData();
                data.remove(ContractEnum.ADD_PAYMENT.getAttr());
                data.remove(ContractEnum.ADD_WRITE_OFF_PREPAYMENT.getAttr());
                data.remove(ContractEnum.ADD_PAYMENT_SHEET.getAttr());
                paasFormDataEntity.setData(data);
                ContractEntityExt contractEntityExt = new ContractEntityExt();
                BeanUtil.copyProperties(paasFormDataEntity, contractEntityExt);
                // 关联产品特殊处理
                JSONObject conDataList = contractEntityExt.getData();
                FormDataUtil.removeSystemData(conDataList);
                Object richTextData = removeRichText(conDataList);
                JSONArray productArray = saasSaveHelp.formatSelectProduct4Save2(conDataList, ContractEnum.PRODUCT.getAttr());
                contractEntityExt.setData(conDataList);

                updateLine = contractModel.update(contractEntityExt);

                // ==========这家客户说，他们的关联产品会丢失，加点日志看看
                List<String> corpidErrors = Arrays.asList("ding8e6733b0f55f17a435c2f4657eb6378f", "ding393d0fe93dab08fd35c2f4657eb6378f");
                for (String corpidError : corpidErrors) {
                    if (Objects.equals(corpidError, formDataUpdateDTO.getCorpid())) {
                        LOG.warn(corpidError + ">>" + "contractId=" + paasFormDataEntity.getId() + " ,serialNo=" + contractEntityExt.getSerialNo() + " ,product=" + JSON.toJSONString(productArray));
                        break;
                    }
                }
                // ============

                contractEntityExt.getData().put(ContractEnum.PRODUCT.getAttr(), productArray);
                // 设置属性用于返回
                setPartialAttributes(contractEntityExt.getSubFormData(), contractEntityExt.getData(),
                        contractEntityExt.getUpdateTime(), contractEntityExt.getAddTime(), contractEntityExt.getSerialNo(),
                        contractEntityExt.getDepartmentId(), contractEntityExt.getOwnerId(),
                        paasFormDataEntity, beforeUpdateVO);
                //文件柜数据保存
                saveFile(formDataUpdateDTO, paasFormDataEntity, userVO);
                //富文本数据更新
                updateFormRichText(formDataUpdateDTO, richTextData);
            }
            updateVO =  new UpdateVO(noApprovalRequired, paasFormDataEntity, updateLine, formDataUpdateDTO.getDataId(), userVO);
            return updateVO;
        } catch (XbbException e) {
            afterSaveRollBack(formDataUpdateDTO, updateVO, beforeUpdateVO, new ReRollBackEntity());
            throw e;
        } catch (Exception e) {
            afterSaveRollBack(formDataUpdateDTO, updateVO, beforeUpdateVO, new ReRollBackEntity());
            LOG.error("customerFormDataUpdateServiceImpl.update 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }


    @Override
    public FormDataUpdateVO afterSave(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, UpdateVO updateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) throws XbbException {
        String corpid = formDataUpdateDTO.getCorpid();
        Long dataId = formDataUpdateDTO.getDataId();
        Integer businessType = formDataUpdateDTO.getBusinessType();
        try {
            FormDataUpdateVO formDataUpdateVO = new FormDataUpdateVO();
            Integer noApprovalRequired = updateVO.getNoApprovalRequired();
            if (Objects.equals(1, noApprovalRequired)) {
                JSONObject oldData = oldPaasFormDataEntity.getData();
                JSONObject newData = paasFormDataEntity.getData();
                SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
                BeanUtil.copyProperties(formDataUpdateDTO, saasFormSaveDTO);
                packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                // 保存合同后的操作
                AfterSavePojo afterSavePojo = contractService.afterSave(saasFormSaveDTO);
                // fix 直接调com.xbongbong.saas.help.workflow.MarketActivityForStaticHelp.updateMarketActivity
                marketActivityForStaticHelp.updateMarketActivity(paasFormDataEntity, RedundantTemplateTypeEnum.CONTRACT);


                // 更新动态
                if(!Objects.equals(DistributorMarkEnum.DISTRIBUTOR.getCode(),formDataUpdateDTO.getDistributorMark())) {
                    MainBusinessDynamicStrategy dynamicStrategy = dynamicStrategyFactory.getMainBusinessDynamicStrategy(ProjectLogEnum.CONTRACT_UPDATE.getSubType());
                    dynamicStrategy.update(DynamicUpdateDTO.initDynamicUpdateDTO(formDataUpdateDTO, beforeUpdateVO, updateVO));
                }
                // 回款单、回款计划处理
                Runnable runnable = () -> {
                    try {
                        payment(formDataUpdateDTO, beforeUpdateVO, updateVO);
                    } catch (Exception e) {
                        LOG.error("保存合同时保存回款", e);
                    }
                };
                threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);

                // 记录日志
                afterSaveLog(formDataUpdateDTO, paasFormEntity, paasFormDataEntity, oldPaasFormDataEntity, updateVO, beforeUpdateVO);
                String newContractSerialNo = paasFormDataEntity.getSerialNo();
                String oldContractSerialNo = oldPaasFormDataEntity.getSerialNo();
                if (!Objects.equals(oldContractSerialNo, newContractSerialNo)) {
                    ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(paasFormDataEntity.getCorpid(), paasFormDataEntity.getId(), newContractSerialNo, newContractSerialNo);
                    consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.CONTRACT);
                }
                // 机会数据一致性同步
                String newNumber = FastJsonHelper.getStringOrDefaultFromFormData(newData, CustomerManagementEnum.NAME.getAttr(), "");
                String oldNumber = FastJsonHelper.getStringOrDefaultFromFormData(oldData, CustomerManagementEnum.NAME.getAttr(), "");
                if (!Objects.equals(oldNumber, newNumber)) {
                    LOG.info("sales opportunity update number : corpid= " + corpid + ">dataId=" + dataId + ">newName="+ newNumber + ">oldName="+ oldNumber);
                    ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(corpid, dataId, newNumber);
                    consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.SALES_OPPORTUNITY);
                }

                // api发起
                apiHook(formDataUpdateDTO, updateVO, beforeUpdateVO);
                // 2021/3/3 业务规则
                activeRule(formDataUpdateDTO, beforeUpdateVO, updateVO);
                formDataUpdateVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
                formDataUpdateVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
            } else if (Objects.equals(noApprovalRequired, 2)) {
                // 自动拒绝
                formDataUpdateVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_PROCESS_RETURN_MSG));
                formDataUpdateVO.setCode(PaasConstant.FORM_ADD_PROCESS_RETURN_CODE);
            } else {
                formDataUpdateVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_PROCESS_RETURN_MSG));
                formDataUpdateVO.setCode(PaasConstant.FORM_ADD_PROCESS_RETURN_CODE);
                PaasProcessDataEntity paasProcessDataEntity = new PaasProcessDataEntity();
                paasProcessDataEntity.setCorpid(formDataUpdateDTO.getCorpid());
                paasProcessDataEntity.setFormDataId(dataId);
                paasProcessDataEntity.setBusinessType(businessType);
                paasProcessDataEntity.setSaasMark(formDataUpdateDTO.getSaasMark());
                proModelService.updateFormDataStatus(paasProcessDataEntity, FlowStatusEnum.IN_APPROVAL.getType());
            }
            formDataUpdateVO.setFormDataId(dataId);
            return formDataUpdateVO;
        } catch (XbbException e) {
            afterSaveRollBack(formDataUpdateDTO, updateVO, beforeUpdateVO, new ReRollBackEntity());
            throw e;
        } catch (Exception e) {
            afterSaveRollBack(formDataUpdateDTO, updateVO, beforeUpdateVO, new ReRollBackEntity());
            LOG.error("customerFormDataUpdateServiceImpl.afterSave 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public void apiHook(FormDataUpdateDTO formDataUpdateDTO, UpdateVO updateVO, BeforeUpdateVO beforeUpdateVO) throws XbbException {
        // 第三方服务
        lowCodeExecuteService(formDataUpdateDTO, updateVO, beforeUpdateVO);
    }

    /**
     * 处理回款计划和回款单
     * @param formDataUpdateDTO
     * @param beforeUpdateVO
     * @param updateVO
     * @return void
     * @author 吴峰
     * @date 2021/3/11 16:18
     * @throws XbbException
     */
    private void payment(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, UpdateVO updateVO) throws XbbException {
        try {
            PaasFormDataEntity paasFormDataEntity = updateVO.getPaasFormDataEntity();
            Double realPaymentTotalAmount = 0.0D;
            SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo = beforeUpdateVO.getSaasNeedRedundantAttrPojo();
            boolean isWorkflowCompany = commonHelp.isOpenWorkFlow(formDataUpdateDTO.getCorpid());
            PaymentDTO paymentDTO = new PaymentDTO();
            if (saasNeedRedundantAttrPoJo != null ) {
                Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(paasFormDataEntity.getData(), ContractEnum.LINK_CUSTOMER.getAttr(), 0L);
                if ( saasNeedRedundantAttrPoJo.getAddBatchDTO() != null ) {
                    BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddBatchDTO(), paymentDTO);
                    paymentDTO.setIsImport(formDataUpdateDTO.getIsImport());
                    if (Objects.nonNull(formDataUpdateDTO.getIsFromProcess()) && Objects.equals(formDataUpdateDTO.getIsFromProcess(), 1)) {
                        paymentDTO.setProcessCreatorId(paasFormDataEntity.getCreatorId());
                    }
                    paymentService.pay(paymentDTO);
                }
//                Double realPaymentTotalAmount = 0.0D;
                if ( saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO() != null ) {
                    PaymentSheetDTO paymentSheetDTO = new PaymentSheetDTO();
                    BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO(), paymentSheetDTO);
                    if (Objects.nonNull(formDataUpdateDTO.getIsFromProcess()) && Objects.equals(formDataUpdateDTO.getIsFromProcess(), 1)) {
                        // 审批
                        paymentSheetDTO.setProcessCreatorId(paasFormDataEntity.getCreatorId());
                    } else {
                        // 不走审批
                        paymentSheetDTO.setProcessCreatorId(formDataUpdateDTO.getUserId());
                    }
                    //区分工作流公司
                    if(isWorkflowCompany){
                        paymentSheetService.addBatchForWorkflow(paymentSheetDTO, PaymentSheetTypeEnum.WRITE_OFF_PREPAYMENT, customerId);
                    }else {
                        PaymentSheetAmountVO writeOffPrepaymentAmountVO = paymentSheetService.addBatch(paymentSheetDTO, PaymentSheetTypeEnum.WRITE_OFF_PREPAYMENT, customerId);
                        realPaymentTotalAmount = writeOffPrepaymentAmountVO.getRealPaymentTotalAmount();
                    }
                }
                if ( saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO() != null ) {
                    PaymentSheetDTO paymentSheetDTO = new PaymentSheetDTO();
                    BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO(), paymentSheetDTO);
                    if (Objects.nonNull(formDataUpdateDTO.getIsFromProcess()) && Objects.equals(formDataUpdateDTO.getIsFromProcess(), 1)) {
                        // 审批
                        paymentSheetDTO.setProcessCreatorId(paasFormDataEntity.getCreatorId());
                    } else {
                        // 不走审批
                        paymentSheetDTO.setProcessCreatorId(formDataUpdateDTO.getUserId());
                    }
                    //区分工作流公司
                    if(isWorkflowCompany){
                        paymentSheetService.addBatchForWorkflow(paymentSheetDTO, PaymentSheetTypeEnum.WRITE_OFF, customerId);
                    }else {
                        PaymentSheetAmountVO writeOffAmountVO = paymentSheetService.addBatch(paymentSheetDTO, PaymentSheetTypeEnum.WRITE_OFF, customerId);
                        Double addPaymentAmount = writeOffAmountVO.getRealPaymentTotalAmount();
                        realPaymentTotalAmount = Arith.add(realPaymentTotalAmount, addPaymentAmount);
                    }
                }
                /**
                 * 处理合同的已回款金额和未收款金额，坏账金额
                 * @author chenshan
                 * @date 2019-11-30 12:47
                 */
                if ( realPaymentTotalAmount > 0.0D && !isWorkflowCompany ) {
                    // 更新现金毛利
                    contractService.updateCashProfit(formDataUpdateDTO.getCorpid(), realPaymentTotalAmount, paasFormDataEntity.getId(), paasFormDataEntity, formDataUpdateDTO.getDistributorMark());
                }
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("contractFormDataUpdateServiceImpl.afterSave 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public UpdateVO updateForWorkflow(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) throws XbbException {
        UpdateVO updateVO = null;
        try {
            UserVO userVO = userHelp.getUserName(formDataUpdateDTO.getCorpid(), formDataUpdateDTO.getUserId(), formDataUpdateDTO.getLoginUserName(), beforeUpdateVO.getPaasFormDataEntity().getFlowStatus(), beforeUpdateVO.getPaasFormDataEntity().getCreatorId());
            Integer noApprovalRequired = beforeUpdateVO.getNoApprovalRequired();
            Integer updateLine = 0;
            JSONObject data = paasFormDataEntity.getData();

            JSONObject originData = (JSONObject) data.clone();

            data.remove(ContractEnum.ADD_PAYMENT.getAttr());
            data.remove(ContractEnum.ADD_WRITE_OFF_PREPAYMENT.getAttr());
            data.remove(ContractEnum.ADD_PAYMENT_SHEET.getAttr());
            paasFormDataEntity.setData(data);
            ContractEntityExt contractEntityExt = new ContractEntityExt();
            BeanUtil.copyProperties(paasFormDataEntity, contractEntityExt);
            // 关联产品特殊处理
            JSONObject conDataList = contractEntityExt.getData();
            FormDataUtil.removeSystemData(conDataList);
            Object richTextData = removeRichText(conDataList);
            JSONArray productArray = saasSaveHelp.formatSelectProduct4Save2(conDataList, ContractEnum.PRODUCT.getAttr());
            contractEntityExt.setData(conDataList);

            updateLine = contractModel.update(contractEntityExt);
            contractEntityExt.getData().put(ContractEnum.PRODUCT.getAttr(), productArray);
            // 设置属性用于返回
            setPartialAttributes(contractEntityExt.getSubFormData(), contractEntityExt.getData(), contractEntityExt.getUpdateTime(), contractEntityExt.getAddTime(), contractEntityExt.getSerialNo(), contractEntityExt.getDepartmentId(), contractEntityExt.getOwnerId(), paasFormDataEntity, beforeUpdateVO);
            //文件柜数据保存
//            saveFile(formDataUpdateDTO, paasFormDataEntity, userVO);
            //富文本数据保存
            Integer updateRichTextLine = updateFormRichText(formDataUpdateDTO, richTextData);
            //表单数据和富文本数据其中有一个编辑就要进工作流
            updateLine = Objects.equals(updateLine, 1) || Objects.equals(updateRichTextLine, 1) ? 1 : 0;

            // 把原始的数据保存，传下去
            paasFormDataEntity.setData(originData);
            updateVO =  new UpdateVO(noApprovalRequired, paasFormDataEntity, updateLine, formDataUpdateDTO.getDataId(), userVO);
            return updateVO;
        } catch (XbbException e) {
            afterSaveRollBack(formDataUpdateDTO, updateVO, beforeUpdateVO, new ReRollBackEntity());
            throw e;
        } catch (Exception e) {
            afterSaveRollBack(formDataUpdateDTO, updateVO, beforeUpdateVO, new ReRollBackEntity());
            LOG.error("customerFormDataUpdateServiceImpl.update 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public FormDataUpdateVO afterSaveForWorkflow(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, UpdateVO updateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) throws XbbException {
        String corpid = formDataUpdateDTO.getCorpid();
        Long dataId = formDataUpdateDTO.getDataId();
        Integer businessType = formDataUpdateDTO.getBusinessType();
        try {
            FormDataUpdateVO formDataUpdateVO = new FormDataUpdateVO();
//            Integer noApprovalRequired = updateVO.getNoApprovalRequired();

            SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
            BeanUtil.copyProperties(formDataUpdateDTO, saasFormSaveDTO);
            packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);

            // 保存合同后的操作
            contractService.afterSaveForUpdateWorkflow(saasFormSaveDTO);
            // 回款单、回款计划处理
//            payment(formDataUpdateDTO, beforeUpdateVO, updateVO);

//            String newContractSerialNo = paasFormDataEntity.getSerialNo();
//            String oldContractSerialNo = oldPaasFormDataEntity.getSerialNo();
//            if (!Objects.equals(oldContractSerialNo, newContractSerialNo)) {
//                ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(paasFormDataEntity.getCorpid(), paasFormDataEntity.getId(), newContractSerialNo, newContractSerialNo);
//                consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.CONTRACT);
//            }
//            // api发起
//            apiHook(formDataUpdateDTO, updateVO, beforeUpdateVO);
//
//            // 2021/3/3 业务规则
//            activeRule(formDataUpdateDTO, beforeUpdateVO, updateVO);
//
            formDataUpdateVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
            formDataUpdateVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
//            PaasProcessDataEntity paasProcessDataEntity = new PaasProcessDataEntity();
//            paasProcessDataEntity.setCorpid(formDataUpdateDTO.getCorpid());
//            paasProcessDataEntity.setFormDataId(dataId);
//            paasProcessDataEntity.setBusinessType(businessType);
//            paasProcessDataEntity.setSaasMark(formDataUpdateDTO.getSaasMark());
            // 更新主表数据在审批中
//            proModelService.updateFormDataStatus(paasProcessDataEntity, FlowStatusEnum.IN_APPROVAL.getType());
            formDataUpdateVO.setFormDataId(dataId);
            return formDataUpdateVO;
        } catch (XbbException e) {
            afterSaveRollBack(formDataUpdateDTO, updateVO, beforeUpdateVO, new ReRollBackEntity());
            throw e;
        } catch (Exception e) {
            afterSaveRollBack(formDataUpdateDTO, updateVO, beforeUpdateVO, new ReRollBackEntity());
            LOG.error("com.xbongbong.paas.service.impl.ContractFormDataUpdateServiceImpl.afterSaveForWorkflow 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public Long backupData(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity formData)  throws XbbException {
        String corpid = formDataUpdateDTO.getCorpid();
        if (!formDataUpdateDTO.getIsSatisfyTrigger()) {
            return null;
        }
        JSONObject data = formData.getData();
        setSystemData(data, formData);
        long now = DateTimeUtil.getInt();
        data = backupDataOtherInfo(data, corpid, formData.getId());
        WorkflowBackupDataEntity workflowBackupDataEntity = new WorkflowBackupDataEntity(corpid, formData.getAppId(), formData.getFormId(), formData.getMenuId(), 0L, 0L,
                formData.getId(), data, now, now, DelEnum.NORMAL.getDel());
        workflowBackupDataModel.insert(workflowBackupDataEntity);
        //富文本数据备份
        backupRichText(workflowBackupDataEntity, formDataUpdateDTO.getBusinessType(), formDataUpdateDTO.getSaasMark());
        return workflowBackupDataEntity.getId();
    }

    @Override
    public JSONObject backupDataOtherInfo(JSONObject data, String corpid, Long dataId) {
        List<ContractUserEntity> contactList = contractUserModel.getContractUserList(corpid, dataId, null);
        data.put(StringConstant.USER_TEAM, contactList);
        List<ContractProductEntity> productList = contractProductModel.getProductsByConId(dataId, corpid);
        data.put(StringConstant.PRODUCT, productList);
        return data;
    }
}
